package com.a01_2021.thousandstimes.instance.controller;


import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.jwt.JwtTokenUtil;
import com.a01_2021.thousandstimes.instance.entity.Vote;
import com.a01_2021.thousandstimes.instance.service.IVoteService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author E1xP
 * @since 2021-03-28
 */
@RestController
@RequestMapping("/vote")
public class VoteController {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    IVoteService voteService;

    /**
     * 用于获取评分列表
     *
     * @param token jwt令牌
     * @return AjaxResponse
     * @throws CustomException 不应当抛出该异常
     */
    @PreAuthorize("hasAuthority('vote-getToVote')")
    @DS("#header.instanceid")
    @PostMapping("getToVote")
    public AjaxResponse getToVote(@RequestHeader("${jwt.header}") String token) throws CustomException {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        Map<String, Object> voteList = voteService.getToVote(userId);
        return AjaxResponse.success(voteList);
    }

    /**
     * 用于提价评分结果
     *
     * @param token    jwt令牌
     * @param voteList 评分列表
     * @return AjaxResponse
     * @throws CustomException 当评分不存在，评分不属于该用户时抛出该异常
     */
    @PreAuthorize("hasAuthority('vote-vote')")
    @DS("#header.instanceid")
    @PostMapping("vote")
    public AjaxResponse vote(@RequestHeader("${jwt.header}") String token, @RequestBody List<Vote> voteList) throws CustomException {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        Map<String, Object> resultMap = voteService.vote(userId, voteList);
        return AjaxResponse.success(resultMap);
    }
}
